package com.ourcraft.informationcollectionsystem.service.province.investigationManage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ourcraft.informationcollectionsystem.entity.Company;
import com.ourcraft.informationcollectionsystem.entity.DataReportForm;
import com.ourcraft.informationcollectionsystem.entity.InvestigationPeriod;
import com.ourcraft.informationcollectionsystem.mapper.CompanyMapper;
import com.ourcraft.informationcollectionsystem.mapper.DataReportFormMapper;
import com.ourcraft.informationcollectionsystem.mapper.InvestigationPeriodMapper;
import com.ourcraft.informationcollectionsystem.utils.statusCode.DataReportFormStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 调查期管理模块调查期相关的服务实现
 *
 * @author Z0136
 * @since 2023/11/4
 */
@Service
public class InvestigationManageServiceImpl implements InvestigationManageService {
    @Autowired
    InvestigationPeriodMapper investigationPeriodMapper;
    @Autowired
    DataReportFormMapper dataReportFormMapper;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    DataReportFormService dataReportFormService;

    /**
     * 删除调查期
     *
     * @param investigationId 删除的调查期Id
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteInvestigation(int investigationId) {
        // 创建一个查询条件，用于查询该调查期是否有已提交企业数据表单
        QueryWrapper<DataReportForm> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("form_examine_status", DataReportFormStatus.NOT_SUBMIT.status).eq("investigation_id", investigationId);
        // 若该调查期已存在已提交的企业数据表单，则不可删除调查期
        if (dataReportFormMapper.selectCount(queryWrapper) > 0)
            return false;
        // 删除调查周期
        return investigationPeriodMapper.deleteById(investigationId) > 0;
    }

    /**
     * 创建新调查期
     *
     * @param investigation 创建的调查期属性
     * @return 是否创建成功
     */
    @Override
    public Boolean createInvestigation(InvestigationPeriod investigation) {
        int success = investigationPeriodMapper.insert(investigation);
        if (success == 0) return false;

        // 获取所有未注销企业信息
        List<Company> companies = companyMapper.selectActiveCompanyIds();

        // 查询上一次调查期
        QueryWrapper<InvestigationPeriod> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lt("investigation_id", investigation.getInvestigationId())
                .orderByDesc("investigation_id").last("LIMIT 1");
        InvestigationPeriod lastInvestigation = investigationPeriodMapper.selectOne(queryWrapper1);

        // 查询上一次调查期的企业数据表单
        QueryWrapper<DataReportForm> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("investigation_id", lastInvestigation.getInvestigationId())
                .orderByAsc("company_id");
        List<DataReportForm> lastReports = dataReportFormMapper.selectList(queryWrapper2);

        // 计算新表单的建档期数据
        List<DataReportForm> newReports = new ArrayList<>();
        int i = 0;
        // 为每一个企业的新表单计算建档期数据
        for (Company company : companies) {
            int id = company.getCompanyId();
            while (i < lastReports.size() && lastReports.get(i).getCompanyId() < id) i += 1;
            // 不存在上一个调查期的数据则设置为null
            if (i == lastReports.size() || lastReports.get(i).getCompanyId() > id)
                newReports.add(new DataReportForm(investigation.getInvestigationId(),
                        id, null));
                // 存在上一个调查期的数据则设置建档期数据为上一次的统计数据
            else
                newReports.add(new DataReportForm(investigation.getInvestigationId(),
                        id, lastReports.get(i).getFormEndTotalNum()));
        }
//        newReports.forEach(report -> dataReportFormMapper.insert(report));
        // 批量创建新调查期企业数据填报表单
        dataReportFormService.saveBatch(newReports);

//            TODO: 此处需要发送通知

        return true;
    }

    /**
     * 修改调查期
     *
     * @param investigation 修改后调查期属性
     * @return 是否修改成功
     */
    @Override
    public Boolean modifyInvestigation(InvestigationPeriod investigation) {
        return investigationPeriodMapper.updateById(investigation) > 0;
    }

    /**
     * 查询所有调查期信息
     *
     * @return 所有调查期信息
     */
    @Override
    public List<InvestigationPeriod> getAllInvestigationInfo() {
        return investigationPeriodMapper.selectList(null);
    }
}
